import { useState, useEffect, FC, ChangeEvent } from 'react';
import { Modal, Input, Button, Typography, message, Spin, Descriptions } from 'antd';
import './SettingCursorPath.css';
import { CursorPaths } from '../../types';

const initialPaths: CursorPaths = {
    storage_path: '',
    sqlite_path: '',
    machine_id_path: '',
    cursor_path: '',
    updater_path: '',
    update_yml_path: '',
    product_json_path: '',
};

interface SettingCursorPathProps {
    open: boolean;
    onClose: () => void;
}

export const SettingCursorPath: FC<SettingCursorPathProps> = ({ open, onClose }) => {
    const [paths, setPaths] = useState<CursorPaths>(initialPaths);
    const [loading, setLoading] = useState(false);
    
    const loadAndSetPaths = async (forceDetect = false) => {
        setLoading(true);
        try {
            let foundPaths: Partial<CursorPaths> | null = null;
            if (!forceDetect) {
                foundPaths = await window.electronAPI.runTask<CursorPaths>('paths:get-stored');
            }

            // If no stored paths or forcing detection, auto-detect.
            if (!foundPaths || Object.keys(foundPaths).length === 0) {
                foundPaths = await window.electronAPI.runTask<CursorPaths>('paths:auto-detect');
                if (foundPaths && Object.keys(foundPaths).length > 0) {
                    // Immediately save the newly detected paths.
                    await window.electronAPI.runTask('paths:set-stored', foundPaths);
                }
            }
            
            setPaths({ ...initialPaths, ...foundPaths });

        } catch (error) {
            message.error('获取或检测路径失败，请手动设置');
            console.error("Error loading paths:", error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (open) {
            loadAndSetPaths();
        }
    }, [open]);

    const handleSave = async () => {
        if (!paths.cursor_path.trim()) {
            message.warning('Cursor 主路径不能为空');
            return;
        }
        setLoading(true);
        try {
            await window.electronAPI.runTask('paths:set-stored', paths);
            message.success('路径已保存');
            onClose();
        } catch (error) {
             message.error('保存路径失败');
        } finally {
            setLoading(false);
        }
    };

    const handleReset = async () => {
        setLoading(true);
        try {
            await window.electronAPI.runTask('paths:clear-stored');
            // After clearing, force re-detection and saving.
            await loadAndSetPaths(true);
            message.success('已重置为自动检测的路径并保存');
        } catch (error) {
            message.error('重置路径失败');
        } finally {
            setLoading(false);
        }
    };
    
    const handlePathChange = (key: keyof CursorPaths, value: string) => {
        setPaths((prev: CursorPaths) => ({...prev, [key]: value}));
    }

    return (
        <Modal
            title="设置 Cursor 路径"
            open={open}
            onOk={handleSave}
            onCancel={onClose}
            width={720}
            footer={[
                <Button key="back" onClick={onClose}>取消</Button>,
                <Button key="reset" onClick={handleReset} loading={loading}>重置</Button>,
                <Button key="submit" type="primary" onClick={handleSave} loading={loading}>保存</Button>,
            ]}
        >
            <Spin spinning={loading} tip="正在检测...">
                <Typography.Paragraph type="secondary">
                    应用需要知道 Cursor 的安装路径以执行某些操作。通常可以自动检测，如果检测不准，请手动设置。
                </Typography.Paragraph>
                
                <Descriptions bordered column={1} size="small" className="paths-descriptions">
                    {Object.keys(paths).map((key) => (
                        <Descriptions.Item label={key.replace(/_/g, ' ')} key={key}>
                            <Input 
                                size="small"
                                value={paths[key as keyof CursorPaths]}
                                onChange={(e: ChangeEvent<HTMLInputElement>) => handlePathChange(key as keyof CursorPaths, e.target.value)}
                            />
                        </Descriptions.Item>
                    ))}
                </Descriptions>
            </Spin>
        </Modal>
    );
}; 